from flask import g
from flask import request
from flask import session, jsonify

from info import redis_store
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
import logging
from flask import current_app,render_template


# 首页新闻列表
# 请求路径: /newslist
# 请求方式:GET
# 请求参数: cid,page,per_page
# cid:分类编号, page 当前页, per_page:显示条数
# 返回值: data数据
@index_blue.route("/newslist")
def newslist():
    """
    1.获取参数
    2.参数类型转化,(因为后面分页时候的,属性都是整形)
    3.分页查询
    4.获取到分页对象中的属性,总页数,当前页,当前页的对象列表
    5.将对象列表转成字典列表
    6.携带数据,返回响应
    """
    # """
    # 1.获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")

    # 2.参数类型转化,(因为后面分页时候的,属性都是整形).
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 3.分页查询
    try:
        # 判断新闻的分类是否为1
        if cid == '1':
            paginate = News.query.filter(News.status == 0).order_by(News.create_time.desc()).paginate(page,per_page,False)
        else:
            paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,per_page,False)

    except Exception as e:
        current_app.logger.error(e)

    # 4.获取到分页对象中的属性,总页数,当前页,当前页的对象列表

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.将对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    # 6.携带数据,返回响应
    return jsonify(errno=RET.OK,errmsg="获取新闻成功",totalPage=totalPage,currentPage=currentPage,newsList=news_list)



# 首页
@index_blue.route("/",methods=["POST","GET"])
@user_login_data
def hello():

    # 3.查询热门新闻,根据点击量,查询前十条新闻
    try:
        news = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    # 4.将新闻对象列表转成,字典列表
    news_list = []
    for item in news:
        news_list.append(item.to_dict())

    # 5.查询所有的分类数据
    try:
        categorties = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取分类失败")

    # 6.将分类对象列表转成,字典列表
    categort_list = []
    for categort in categorties:
        categort_list.append(categort.to_dict())


    # 3.拼接用户数据渲染页面
    data = {
        "user_info":g.user.to_dict() if g.user else "",
        "news":news_list,
        "categort_list":categort_list,
    }
    return render_template("news/index.html",data=data)


# 处理网站logo
# current_app.send_static_file: 会自动去静态文件static中寻找文件
@index_blue.route('/favicon.ico')
def get_web_logo():

    return current_app.send_static_file("news/favicon.ico")


# 统一的返回404页面s
@index_blue.route('/404')
@user_login_data
def page_not_found():
    data = {
        "user_info":g.user.to_dict() if g.user else ""
    }
    return render_template("news/404.html",data=data)
